package com.xlcszsgc.module.blob.ui.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xlcszsgc.module.blob.domain.BaseBlob;
import com.xlcszsgc.module.blob.service.IBlobService;
import com.xlcszsgc.module.blob.ui.commond.BaseBlobCommond;

/**
 * @Title: BaseBlobController.java
 * @Package com.xlcszsgc.module.blob.ui.controller
 * @Description: blob控制器
 * @author Zhaoqt  
 * @date 2014-5-26 上午12:07:08
 * @version V1.0
 */
@Controller
@RequestMapping(value = {BaseBlobController.portalPath, BaseBlobController.modulePath})
public class BaseBlobController {

	public static final String modulePath = "/module/baseblob";
	
	public static final String portalPath = "/portal/baseblob";
	
	@Resource(name = "com.xlcszsgc.module.blob.service.impl.BlobServiceImpl")
	private IBlobService blobService;
	
	@RequestMapping("/showImage")
	public void showImage(HttpServletResponse resp, BaseBlobCommond baseBlobCommond)
	    throws Exception
	  {
	    OutputStream writer = null;
	    BufferedOutputStream bufferWriter = null;
	    InputStream reader = null;
	    BufferedInputStream bufferReader = null;
	    
	    int BUFFERSIZE = 4096;
	    try
	    {
	      BaseBlob entity = this.blobService.getBaseBlob(baseBlobCommond);
	      if (entity != null)
	      {
	        Blob blob = entity.getBlob();
	        writer = resp.getOutputStream();
	        bufferWriter = new BufferedOutputStream(writer);
	        reader = blob.getBinaryStream();
	        bufferReader = new BufferedInputStream(reader);
	        resp.setContentType("image/jpeg");
	        int i = 0;
	        byte[] bytes = new byte[BUFFERSIZE];
	        while ((i = bufferReader.read(bytes)) != -1) {
	          bufferWriter.write(bytes, 0, i);
	        }
	        bufferWriter.flush();
	      }
	    }
	    catch (Exception e)
	    {
	      e.printStackTrace();
	    }
	    finally
	    {
	      if (bufferWriter != null) {
	        bufferWriter.close();
	      }
	      if (bufferReader != null) {
	        bufferReader.close();
	      }
	      if (writer != null) {
	        writer.close();
	      }
	      if (reader != null) {
	        reader.close();
	      }
	    }
	  }
}
